package ldh.im.fxbase;

import ldh.im.fxbase.util.DbUtil;
import ldh.im.fxbase.util.JarUtil;
import ldh.im.fxbase.util.LoggerUtil;
import ldh.im.util.ConfigUtil;
import org.slf4j.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.ResourceBundle;

public class InitDb {

    private static final Logger LOGGER = LoggerUtil.getFileLogger(InitDb.class);

    public void initDb(String dataDir) throws SQLException {
        String sqlFile = getInitSqlFile();
        LOGGER.info("init sql file: {}", sqlFile);
        checkOrInitDb(dataDir, sqlFile);
    }

    private void checkOrInitDb(String dataDir, String sqlFile) throws SQLException {
        try {
//            String file = getDataFile(File.separator + "data" + File.separator + "db" + File.separator + "im.mv.db");
            String dbFileName = ConfigUtil.getString("im.name") + ".mv.db";
            String file = dataDir + File.separator + "db" + File.separator + dbFileName;
            LOGGER.info("check db is installed! file:" + file);
            if(sqlFile.startsWith("file:/")) sqlFile = sqlFile.substring(6);
            File f = new File(file);
            if (!f.exists()) {
                if (JarUtil.isJarFile(sqlFile)) {
                    String sql = JarUtil.readContent(sqlFile);
                    initSql(sql);
                } else if (sqlFile.startsWith("resource")){
                    String tmpFile = sqlFile.substring("resource".length()+2);
                    LOGGER.info("check db is installed! file2:" + tmpFile);
                    try (InputStream sqlFileInputStream = InitDb.class.getClassLoader().getResourceAsStream(tmpFile)) {
                        String sql = new String(sqlFileInputStream.readAllBytes(), "utf8");
                        initSql(sql);
                    }
                } else {
                    try (InputStream sqlFileInputStream = new FileInputStream(sqlFile)) {
                        String sql = new String(sqlFileInputStream.readAllBytes(), "utf8");
                        initSql(sql);
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("checkDb error!!!!!!!!!!!!!!!!!!", e);
        }
        checkOnlyOne();
//        checkChangeSql();
        LOGGER.info("checkDb end!!!!!!!!!!!!!!!!!!");
    }

    protected int initSql(String sql) throws SQLException {
        return DbUtil.transaction((queryRunner, connection) -> {
            LOGGER.info("handel sql: " + sql);
            return queryRunner.execute(connection, sql);
        });
    }

    protected void checkOnlyOne() throws SQLException {
        DbUtil.transaction((queryRunner, connection) -> {
            String sql = "select count(1) from im_cache_login_user";
            return queryRunner.execute(connection, sql);
        });
    }

    private String getImSql(String sqlFile) {
        String sql = "";
        try {
            sql = Files.readString(Paths.get(sqlFile));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return sql;
    }

    private String getDataFile(String file) {
        String root = System.getProperty("user.dir");
        String dir = root + file;
        return dir;
    }


    private void checkChangeSql() {
        try {
            String sqlFile = getDataFile(File.separator + "doc" + File.separator + "client" + File.separator + "imgui-ch.sql");
            LOGGER.info("checkChangeSql:" + sqlFile);
            File f = new File(sqlFile);
            if (f.exists()) {
                initSql(Files.readString(Paths.get(sqlFile)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getInitSqlFile() {
        String root = System.getProperty("user.dir");
        String fileName = ConfigUtil.getString("im.name") + "-h2.sql";
        String sqlFile = root + File.separator + "doc" + File.separator + "client" + File.separator + fileName;
        LOGGER.info("initSql file:" + sqlFile);
        try {
            if (Paths.get(sqlFile) == null || !Files.exists(Paths.get(sqlFile))) {
                sqlFile = InitDb.class.getResource("/ldh/im/fxbase/sql/" + fileName).toExternalForm();
            }
        } catch (Exception e) {
            try {
                sqlFile = InitDb.class.getResource("/ldh/im/fxbase/sql/" + fileName).toExternalForm();
            } catch (Exception ee) {
                sqlFile = InitDb.class.getClassLoader().getResource("/ldh/im/fxbase/sql/" + fileName).toExternalForm();
            }
        }
        return sqlFile;
    }
}
